package cn.com.obs;

import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import io.minio.MinioClient;
import io.minio.credentials.LdapIdentityProvider;
import okhttp3.OkHttpClient;

public class MinioLdapManager {

    private MinioClient minioClient;

    // 获取忽略证书验证的 OkHttpClient
    private OkHttpClient getUnsafeOkHttpClient() {
        try {
            // 创建一个不验证证书链的 TrustManager
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[] {};
                        }
                    }
            };

            // 安装全信任的 TrustManager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // 创建一个不进行主机名验证的 HostnameVerifier
            final HostnameVerifier hostnameVerifier = (hostname, session) -> true;

            // 构建一个 OkHttpClient 实例
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(hostnameVerifier);
            builder.connectTimeout(30, TimeUnit.SECONDS);
            builder.readTimeout(30, TimeUnit.SECONDS);
            builder.writeTimeout(30, TimeUnit.SECONDS);
            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public MinioLdapManager(String endpoint, String accessKey, String secretKey, String stsEndpoint, String ldapUser, String ldapPassword) {
        // 使用 LDAP 身份验证创建 MinIO 客户端
        OkHttpClient unsafeHttpClient = getUnsafeOkHttpClient();
        LdapIdentityProvider ldapProvider = new LdapIdentityProvider(stsEndpoint, ldapUser, ldapPassword, unsafeHttpClient);

        this.minioClient = MinioClient.builder()
                                      .endpoint(endpoint)
                                      .credentialsProvider(ldapProvider)
                                      .build();
    }

    // 示例方法：列出桶
    public void listBuckets() {
        try {
            minioClient.listBuckets().forEach(bucket -> System.out.println(bucket.name()));
        } catch (Exception e) {
            System.err.println("Error occurred: " + e);
        }
    }

    public static void main(String[] args) {
        String endpoint = "https://minio.example.com";
        String accessKey = "your-access-key";
        String secretKey = "your-secret-key";
        String stsEndpoint = "https://sts.example.com";
        String ldapUser = "ldap-username";
        String ldapPassword = "ldap-password";

        MinioLdapManager manager = new MinioLdapManager(endpoint, accessKey, secretKey, stsEndpoint, ldapUser, ldapPassword);
        manager.listBuckets();
    }
}
